import { templateDef } from "@/api";
import {
  Header,
  TemplateDefEditorAtom,
  TemplateFileFormAtom,
} from "@/components";
import { ResultUtil } from "@/util";
import { useStore } from "@/util/hooks";
import { Button } from "@arco-design/web-react";
import { IconUpload } from "@arco-design/web-react/icon";

interface TemplateDefHeaderProps {
  showAction?: boolean;
}

export const TemplateDefHeader = ({
  showAction = true,
}: TemplateDefHeaderProps) => {
  const formStore = useStore(TemplateFileFormAtom);
  const editorStore = useStore(TemplateDefEditorAtom);

  async function onSaveButtonClick() {
    const data = formStore.value.data!;
    const res = await templateDef.update({
      ...data,
      data: editorStore.value.data || "",
    });
    ResultUtil.showResult(res);
  }

  return (
    <Header
      title="内容"
      extra={
        showAction && (
          <Button
            title="保存"
            icon={<IconUpload />}
            onClick={onSaveButtonClick}
          />
        )
      }
    />
  );
};
